package com.zrc.superframe_tbs

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.FileUtils
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsDownloader
import com.tencent.smtt.sdk.TbsListener
import com.zrc.superframe_net.utils.HawkSpUtitls
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import java.io.File

/**
 * @Author: superman
 * @CreateTime: 10/27/21
 * @Describe:
 */
class TbsUtils {

    data class TbsInitMsg(var state: TbsInitState, var value: Int = 0) {
        enum class TbsInitState {
            TBS_DOWNLOAD,//内核下载结束 value（加载进度0-100）
            TBS_LOADING,//内核加载中 value（0：失败 1：成功）
        }
    }

    companion object {
        const val TAG = "TBS"
        private lateinit var instance: TbsUtils
        private var isInit = false
        fun get(): TbsUtils {
            return if (this::instance.isInitialized) {
                instance
            } else {
                instance = TbsUtils()
                instance
            }
        }
    }

    private lateinit var mContext: Context

    lateinit var liveData: MutableLiveData<TbsInitMsg>

    @SuppressLint("CheckResult")
    fun handleMsg(msg:TbsInitMsg){
        Observable.just(msg)// 回调 主线程
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { liveData.value = it }
    }

    @SuppressLint("LogNotTimber")
    fun init(context: Context) {
        liveData = MutableLiveData<TbsInitMsg>()
        mContext = context
        if (!this::mContext.isInitialized) {
            throw NullPointerException("init fail")
        }
        mContext = context
        isInit = HawkSpUtitls.get("TBS_INIT_ISOK", false)
        if (!isInit) {//只要是之前没加载完成都要重置在加载
            QbSdk.reset(mContext)
            // 在调用TBS初始化、创建WebView之前进行如下配置
            val map = HashMap<String, Any>()
            map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
            map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
            QbSdk.initTbsSettings(map)
            QbSdk.setDownloadWithoutWifi(false)
            QbSdk.disableAutoCreateX5Webview()
            //QbSdk.forceSysWebView(); //强制使用系统内核
            val canload = !TbsDownloader.isDownloading()
            Log.d(TAG, "内核重置完成")
            if (!canload) {
                Log.d(TAG, "内核从新下载")
                TbsDownloader.startDownload(mContext)
            } else {
                Log.d(TAG, "内核正在下载中")
            }
        }
        QbSdk.setTbsListener(object : TbsListener {
            override fun onDownloadFinish(i: Int) {
                //此处存在一种情况，第一次启动app，init不会自动回调，此处额外加一层，判断网络监听器是否为空并作出处理
                if (i == 100) {//成功时i为100
                    Log.d(TAG, "内核下载完成")
                }
            }

            override fun onInstallFinish(i: Int) {
                if (i == 100) {
                    Log.d(TAG, "内核安装完成")
                }
            }

            @SuppressLint("CheckResult")
            override fun onDownloadProgress(i: Int) {
                Log.d(TAG, "内核下载中->$i")
                handleMsg(TbsInitMsg(TbsInitMsg.TbsInitState.TBS_DOWNLOAD, i))
            }
        })
        QbSdk.initX5Environment(context, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
                //x5内核初始化完成回调接口，此接口回调并表示已经加载起来了x5，有可能特殊情况下x5内核加载失败，切换到系统内核。
                Log.e(TAG, "加载内核结束")
            }

            override fun onViewInitFinished(b: Boolean) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。该方法在第一次安装app打开不会回调
                isInit = b
                if (isInit) {
                    Log.e(TAG, "内核加载成功")
                } else {
                    Log.e(TAG, "内核加载失败")
                }
                HawkSpUtitls.save("TBS_INIT_ISOK", isInit)
                handleMsg(TbsInitMsg(TbsInitMsg.TbsInitState.TBS_LOADING, if (isInit) 1 else 0))
            }
        })
    }

    fun isOk(): Boolean = HawkSpUtitls.get("TBS_INIT_ISOK", false)

    private fun getFileExtension(file: File): String = FileUtils.getFileExtension(file)

    fun getFileType(file: File) = getFileExtension(file).replace(".", "")

}